package element.synt;

import ast.AstItem;
import ast.FunctionSignature;
import element.base.BaseNode;
import element.base.Synt;
import element.base.Word;
import element.base.WordType;

import java.util.ArrayList;
import java.util.List;

public class FuncDef extends Synt {

    public AstItem toAst(boolean inClass) {
        FunctionSignature func = new FunctionSignature();
        if (inClass) {
            func.signatureType = FunctionSignature.SignatureType.CLASS_METHOD;
        } else {
            func.signatureType = FunctionSignature.SignatureType.FUNC_DEF;
        }

        func.funcName = ((Word) getNodes().get(1)).getContent();

        if (getNodes().get(3).isSynt(FuncFParams.class)) {
            FuncFParams funcFParams = (FuncFParams) getNodes().get(3);
            List<AstItem> params = funcFParams.toAsts();

            for (int i = 0; i < params.size(); i++) {
                func.parameters.add(params.get(i));
            }
        }

        if (getNodes().get(getNodes().size() - 2).isSynt(ArrayLengths.class)) {
            Type returnType = (Type) getNodes().get(getNodes().size() - 3);
            ArrayLengths arrayLengths = (ArrayLengths) getNodes().get(getNodes().size() - 2);
            List<AstItem> dims = arrayLengths.toAsts();
            int dimCount = dims.size();
            func.returnType = ((Synt) returnType).findFirst().getContent() + "_" + dimCount;
        } else {
            BaseNode returnType = getNodes().get(getNodes().size() - 2);

            if (returnType.isWord(WordType.VOIDTK)) {
                func.returnType = ((Word) returnType).getContent();
            } else {
                func.returnType = ((Synt) returnType).findFirst().getContent();
            }
        }


        ast.FuncDef funcDef = new ast.FuncDef();
        funcDef.funcSignature = func;

        Block funcBlock = ((Block) getNodes().getLast());
        funcDef.funcBlock = funcBlock.toAst();

        return funcDef;
    }
}
